package me.cxlr.qinlauncher2.dao;

import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;
import io.realm.RealmResults;
import io.realm.Sort;
import me.cxlr.qinlauncher2.model.App;
import me.cxlr.qinlauncher2.model.Folder;

/**
 * FolderDao
 *
 * @author 酷安用户:山轮纸
 */
public class FolderDao {
    private Realm realm;

    /**
     * 获取所有文件夹
     *
     * @return List<Folder>
     */
    public List<Folder> findAllFolder() {
        List<Folder> folderList = new ArrayList<>(16);
        try {
            realm = Realm.getInstance(RealmConfig.getRealmConfig());
            RealmResults<Folder> results = realm.where(Folder.class).findAll();
            if (results != null) {
                folderList = realm.copyFromRealm(results);
                realm.close();
                return folderList;
            } else {
                realm.close();
                return folderList;
            }
        } catch (Exception e) {
            Logger.e("getAllFolder" + e.toString());
            return folderList;
        } finally {
            realm.close();
        }
    }

    /**
     * 新建文件夹
     *
     * @param folder Folder
     */
    public void saveFolder(Folder folder) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        realm.beginTransaction();
        Folder tmpList = realm.copyToRealm(folder);
        realm.commitTransaction();
        realm.close();
    }

    /**
     * 修改Folder
     *
     * @param folder 文件夹
     */
    public void updateFolder(Folder folder) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        realm.beginTransaction();
        Folder tmp = realm.copyToRealmOrUpdate(folder);
        realm.commitTransaction();
        realm.close();
    }

    /**
     * 删除文件夹
     *
     * @param folder
     */
    public void deleteFolder(Folder folder) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        realm.beginTransaction();
        Folder tmp = realm.where(Folder.class).equalTo("id", folder.getId()).findFirst();
        if (tmp != null) {
            tmp.deleteFromRealm();
        }
        realm.commitTransaction();
        realm.close();
    }
}
